package com.fattyCorps.common.util;

import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.List;

public class CfgUtils {
    public static <T> List<T> cfgStrToBeanList(String cfgStr, Class<T> cls) {
        final String SPLIT = ",";
        Field[] fields = cls.getDeclaredFields();
        String[] split = cfgStr.split(SPLIT);
        if (split.length % fields.length != 0) {
            throw new RuntimeException("配置参数数量不对 cls=>" + cls.getSimpleName() + " str=>" + cfgStr);
        }

        try {
            T ins = null;
//            T def = cls.newInstance();
            List<T> retList = new ArrayList<>();

            for (int i = 0; i < split.length; i++) {
                int fIdx = i % fields.length;
                if (fIdx == 0) {
                    ins = cls.newInstance();
                }

                Field f = fields[fIdx];
                f.setAccessible(true);

                if (split[i] != null) {
                    if (f.getType() == Integer.class || f.getType() == int.class) {
                        f.set(ins, Integer.valueOf(split[i]));
                    } else if (f.getType() == String.class) {
                        f.set(ins, split[i]);
                    } else {
                        throw new RuntimeException("不支持的类型");
                    }
                }

                if (fIdx == fields.length - 1) {
                    retList.add(ins);
                }
            }

            return retList;
        } catch (InstantiationException | IllegalAccessException e) {
            throw new RuntimeException(e);
        }
    }
}
